// ------------------- Form 控件 的统一布局 -------------------------------
import {useEffect} from "react";
import {Form, message} from "antd";

export  const singleColumnLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16},
};
export  const DoubleColumnLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16},
};
export function useModalFormAction( queryFunction:(id:string)=>Promise<any>,saveFunction:(data:object)=>Promise<void>,onOk:()=>void ,id?:string,){
    useEffect(()=>{
        if(id){
            queryFunction(id).then(e=>{
                form.setFieldsValue(e);
            }) ;
        }
    },[id]);

    const [form] =Form.useForm();

    const onCommit = ()=>{
        let errors= form.getFieldsError();
        let buffer = [];
        // TODO 处理好 提醒
        for(let i in errors){
            if(errors[i].errors.length>0){
                buffer.push(...errors[i].errors);
            }
        }
        if(buffer.length>0){
            message.warn(buffer.join("，"));
            return;
        }
        let data = form.getFieldsValue();
        if(id){
            data = {...data, id};
        }
        saveFunction(data).then(e=>{
            message.warn("保存成功");
            onOk();
        }).catch(e=>{
            message.warn("保存失败")
        })
    };
    return {form, onCommit}
}
